package leetcode;

public class LeetCode35 {

    public static void main(String[] args) {
        LeetCode35 leetCode35 = new LeetCode35();
        leetCode35.searchInsert(new int[]{1, 3, 5, 6}, 2);
    }

    //时间复杂度o(n)
    public int searchInsert1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target)
                return i;
            else if (nums[i] > target)
                return i;
        }
        return nums.length;
    }

    //------------------------------------------------------------------
    //这道题考查目的是二分查找
    //二分查找的前提的数据元素有序
    //每次与中位数进行比较 因为有序可以判断下一个位置在哪
    public int searchInsert(int[] nums, int target) {
        int left = 0, right = nums.length - 1, mid;
        while (left <= right) {
            mid = (left + right) / 2;
            System.out.println("left " + left);
            System.out.println("right " + right);
            System.out.println("mid " + mid);
            System.out.println("------------");
            if (nums[mid] == target)
                return mid;
            else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
}
